package com.bmob.lover.app.ext

import android.content.Context
import android.content.Intent
import android.media.MediaScannerConnection
import android.media.ThumbnailUtils
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.customview.widget.ViewDragHelper
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSON
import com.amap.api.location.AMapLocation
import com.bmob.lover.R
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.Gson
import com.luck.picture.lib.entity.LocalMedia
import com.theone.common.ext.screenWidth
import com.bmob.lover.data.model.bean.UserLocation
import com.theone.common.ext.getColor
import com.theone.loader.LoaderService
import com.theone.mvvm.core.app.util.FileDirectoryManager
import com.theone.mvvm.core.app.util.FileManager
import com.theone.mvvm.core.base.loader.callback.ErrorCallback
import com.theone.mvvm.core.base.loader.callback.LoadingCallback
import com.theone.mvvm.ext.qmui.showFailTipsDialog
import java.io.File
import java.io.FileWriter
import java.io.IOException
import java.io.PrintWriter
import java.util.*
import kotlin.math.abs


//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛k
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021/3/12 0012
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */


fun String.writeStringToFile(path: String = FileDirectoryManager.getCachePath() + File.separator + "temp.txt") {
    try {
        val pw = PrintWriter(FileWriter(path))
        pw.print(this)
        pw.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}


/**
 * 将对象转为JSON字符串
 */
fun Any?.toJson(): String {
    return Gson().toJson(this)
}


private fun Double.toLocationInt(): Int {
    return (this * 100).toInt()
}

private fun Double.getDiff(other: Double): Int {
    return abs(this.toLocationInt() - other.toLocationInt())
}

fun UserLocation.isSameLocation(aMapLocation: AMapLocation): Boolean {
    val lonDiff = longitude.getDiff(aMapLocation.longitude)
    val latDiff = latitude.getDiff(aMapLocation.latitude)
    // 经纬度变化了才更新地理位置
    return lonDiff == 0 && latDiff == 0
}

fun Any?.toJsonWithoutAttr(vararg attrs: String): String {
    return toJson().jsonWithoutAttr(*attrs)
}

fun String?.jsonWithoutAttr(vararg attrs: String): String {
    if (null == this) return ""
    val arrays = JSON.parseObject(this)
    for (attr in attrs) {
        arrays.remove(attr)
    }
    return arrays.toString()
}

/**
 * 加入qq聊天群
 * https://qun.qq.com/join.html
 */
fun Context.joinQQGroup(key: String) {
    val intent = Intent()
    intent.data =
        Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D$key")
    // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    try {
        startActivity(intent)
    } catch (e: Exception) {
        // 未安装手Q或安装的版本不支持
        showFailTipsDialog("未安装手机QQ或安装的版本不支持")
    }
}

//设置适配器的列表动画
fun BaseQuickAdapter<*, *>.setAdapterAnimation(mode: Int?) {
    mode?.let {
        //等于0，关闭列表动画 否则开启
        if (it == 0) {
            animationEnable = false
        } else {
            animationEnable = true
            setAnimationWithDefault(BaseQuickAdapter.AnimationType.values()[it - 1])
        }
    }
}

fun BaseQuickAdapter<*, *>.removeItem(position: Int) {
    if (position != RecyclerView.NO_POSITION && data.size > position) {
        data.removeAt(position)
        notifyItemRemoved(position)
        notifyItemRangeChanged(position, data.size)
    }
}

/**
 * DrawerLayout全屏滑动
 * @param context Context
 * @param drawerLayout DrawerLayout
 * @param dragPercent Float
 */
fun setDrawerLeftEdgeSize(
    context: Context,
    drawerLayout: DrawerLayout,
    dragPercent: Float
) {
    try {
        val leftDrawerField = drawerLayout.javaClass.getDeclaredField("mLeftDragger").apply {
            isAccessible = true
        }
        val helper = leftDrawerField.get(drawerLayout) as ViewDragHelper
        val edgeSizeField = helper.javaClass.getDeclaredField("mEdgeSize").apply {
            isAccessible = true
        }
        val edgeSize = edgeSizeField.getInt(helper)
        val width = context.screenWidth
        edgeSizeField.setInt(
            helper, edgeSize.coerceAtLeast(
                (width * dragPercent).toInt()
            )
        )
    } catch (e: Exception) {
        e.printStackTrace()
    }
}


/**
 * 设置空布局
 */
fun LoaderService.showDarkEmpty() {
    showDarkError("暂无此内容", R.drawable.status_search_result_empty)
}

fun LoaderService.showDarkLoadingPage() {
    showCallbackView(LoadingCallback::class.java){ _, view ->
        view?.run {
            findViewById<TextView>(R.id.loading_tips).apply {
                setTextColor(getColor(R.color.white))
            }
            findViewById<RelativeLayout>(R.id.loadingStateRelativeLayout).setBackgroundColor(
                getColor(R.color.black)
            )
        }
    }
}

/**
 * 设置错误布局
 * @param message 错误布局显示的提示内容
 */
fun LoaderService.showDarkError(
    message: String?,
    imageRes: Int = R.drawable.status_loading_view_loading_fail
) {
    showCallbackView(ErrorCallback::class.java){ _, view ->
        view?.run {
            findViewById<TextView>(R.id.stateContentTextView).apply {
                text = message
                setTextColor(getColor(R.color.white))
            }
            findViewById<ImageView>(R.id.stateImageView).setImageResource(imageRes)
            findViewById<RelativeLayout>(R.id.errorStateRelativeLayout).setBackgroundColor(
                getColor(
                    R.color.black
                )
            )
        }
    }
}


fun getVideoThumbnail(localPath: String): String {
    val bitmap = ThumbnailUtils.createVideoThumbnail(
        localPath,
        MediaStore.Images.Thumbnails.FULL_SCREEN_KIND
    )
    return FileManager.saveBitmap(
        bitmap,
        FileDirectoryManager.getCompressPath() + File.separator + "Thumbnail"
    )
}


private val allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"

val nickname: String by lazy {
    (1..allowedChars.length)
        .map { allowedChars.random() }
        .joinToString("").substring(0, 6)
}

fun Context.deleteFiles(files: List<LocalMedia>) {
    // Android 11
    val isR = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
    val paths = arrayOfNulls<String>(files.size)
    for ((index, file) in files.withIndex()) {
        file.path.let { path ->
            paths[index] = path
            if (!isR)
                File(path).let {
                    if (it.exists()) {
                        it.delete()
                    }
                }
        }
    }
    // Android 11 删除文件
    if (isR) {
        contentResolver.delete(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            MediaStore.Images.Media.DISPLAY_NAME + "=?",
            paths
        )
    }
    // 通知系统刷新文件
    try {
        MediaScannerConnection.scanFile(
            this,
            paths,
            null
        ) { path: String?, uri: Uri? ->

        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
}

private val mFormatBuilder = StringBuilder()
private val mFormatter = Formatter(mFormatBuilder, Locale.getDefault())

fun Long.formatTime(): String {
    val totalSeconds = this / 1000
    val seconds = totalSeconds % 60
    val minutes = (totalSeconds / 60) % 60
    val hours = totalSeconds / 3600
    mFormatBuilder.setLength(0)
    return if (hours > 0) {
        mFormatter.format("%d:%02d:%02d", hours, minutes, seconds)
    } else {
        mFormatter.format("%02d:%02d", minutes, seconds)
    }.toString()

}



